from time import timezone

import datetime
from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

from contents.utils import get_categories
from .models import GoodsCategory, SKU, GoodsVisitCount
from .utils import get_breadcrumb
from django.core.paginator import Paginator, EmptyPage
from .constants import GOODS_LIST_LIMIT
import logging
from meiduo_mall.utils.response_code import RETCODE

logger=logging.getLogger('django')


class DetailVisitCount(View):
    def post(self, request, category_id):

        category=GoodsCategory.objects.get(id=category_id)
        try:
            SKU.objects.get(id=category_id)
        except SKU.DoesNotExist:
            return http.HttpResponseNotFound('category_id不存在')

        t = timezone.localtime()
        time_str = "%d_%02d_%02d" % (t.year,t.month,t.day)
        today_date=datetime.datetime.strptime(time_str,'%Y-%m-%d')

        try:
            count_data=category.goodsvisitcount_set.get(date=today_date)
        except GoodsVisitCount.DoesNotExist:
            count_data=GoodsVisitCount()

        try:
            count_data.category=category
            count_data.count=count_data+1
            count_data.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('服务器异常')

        return http.JsonResponse({'code':RETCODE.OK,'errmsg':"ok"})





class DetailView(View):
    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseNotFound('未找到id')
        categories = get_categories()
        breadcrumb = get_breadcrumb(sku.category)
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.skus.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        context = {
            'sku': sku,
            'categories': categories,
            'breadcrumb': breadcrumb
        }

        return render(request, 'detail.html', context)


class ListView(View):
    def get(self, request, category_id, page_num):
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoseNotExist as e:
            return http.HttpResponseForbidden('查询参数不存在')

        breadcrumb = get_breadcrumb(category)

        categories = get_categories()

        sort = request.GET.get('sort', 'default')

        if sort == 'price':
            sort_field = 'price'
        elif sort == 'hot':
            sort_field = '-sales'
        else:
            sort = 'default'
            sort_field = 'create_time'
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(sort_field)

        paginator = Paginator(skus, GOODS_LIST_LIMIT)

        try:
            page_skus = paginator.page(page_num)
        except EmptyPage:
            http.HttpResponseNotFound('empty page')
        total_page = paginator.num_pages

        context = {'categories': categories,
                   'breadcrumb': breadcrumb,
                   'sort': sort,  # 排序字段
                   'category': category,  # 第三级分类
                   'page_skus': page_skus,  # 分页后数据
                   'total_page': total_page,  # 总页数
                   'page_num': page_num,  # 当前页码
                   }
        return render(request, 'list.html', context)
